package com.bit.cfdi.web.vm;

import java.util.ArrayList;
import java.util.List;

import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.ContextParam;
import org.zkoss.bind.annotation.ContextType;
import org.zkoss.bind.annotation.Init;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Desktop;
import org.zkoss.zk.ui.select.annotation.VariableResolver;
import org.zkoss.zul.Tab;
import org.zkoss.zul.Tabbox;
import org.zkoss.zul.Tabpanel;

@VariableResolver(org.zkoss.zkplus.spring.DelegatingVariableResolver.class)
public class TestTabsViewModel {
	
	//Tabbox used for main container
	private Tabbox toUse;
	
	//Variables
	private Integer selectedIndex;
	private String tabKey;
	
	private List<String> tabs;
	
	@Init
	public void init(@ContextParam(ContextType.DESKTOP) final Desktop desktop) {
		attachTabbox(desktop);
		fillTabs();
		selectedIndex = 0;
	}
	
	//Geters - Setters
	public Integer getSelectedIndex() {
		return selectedIndex;
	}
	
	public void setSelectedIndex(final Integer selectedIndex) {
		this.selectedIndex = selectedIndex;
	}
	
	public String getTabKey() {
		return tabKey;
	}
	
	public void setTabKey(final String tabKey) {
		this.tabKey = tabKey;
	}
	
	@Command @NotifyChange("selectedIndex")
	public void changeSelectedTab() {
		if(!tabs.contains(tabKey)) {
			return;
		}
		selectedIndex = tabs.indexOf(tabKey);
	}
	
	//Private Methods
	private void attachTabbox(
			@ContextParam(ContextType.DESKTOP) final Desktop desktop) {
		
		for(Component currentComponent : desktop.getComponents()) {
			if("tabbox".equals(currentComponent.getId()) &&
					currentComponent instanceof Tabbox) {
				toUse = (Tabbox) currentComponent;
				break;
			}
		}
	}
	
	private void fillTabs() {
		tabs = new ArrayList<String>();
		for(int i=0; i<5; i++) {
			Tab tab = new Tab();
			tab.setLabel("");
			tab.setStyle("visibility:hidden");
			tabs.add(String.valueOf(i));
			toUse.getTabs().appendChild(tab);
			toUse.getTabpanels().appendChild(new Tabpanel());
		}
	}
}
